#页面静态化
from celery_tasks.main import app
from goods.models import SKU
from meiduo_mall.utils.categories import get_categories
from meiduo_mall.utils.breadcrumb import get_breadcrumb
from django.template import loader
from django.conf import settings
@app.task(name='get_detail_html')
def get_detail_html(sku_id):
    try:
        sku = SKU.objects.get(pk=sku_id)
    except:
        raise Exception('商品编号无效')
    categories = get_categories()
    breadcrumb = get_breadcrumb(sku.category)
    spu = sku.spu
    specs = spu.specs.order_by('id')
    skus = spu.skus.order_by('id')
    sku_options = {}
    sku_option = []
    for sku1 in skus:
        infos = sku1.specs.order_by('spec_id')
        option_key = []
        for info in infos:
            option_key.append(info.option_id)
            if sku.id == sku1.id:
                sku_option.append(info.option_id)
        sku_options[tuple(option_key)] = sku1.id
#     遍历
    specs_list = []
    for index, spec in enumerate(specs):
        option_list = []
        for option in spec.options.all():
            # 如果当前商品为蓝、64,则列表为[2,3]
            sku_option_temp = sku_option[:]
            # 替换对应索引的元素：规格的索引是固定的[1,3]
            sku_option_temp[index] = option.id
            # 为选项添加sku_id属性，用于在html中输出链接
            option.sku_id = sku_options.get(tuple(sku_option_temp), 0)
            # 添加选项对象
            option_list.append(option)
        # 为规格对象添加选项列表
        spec.option_list = option_list
        # 重新构造规格数据
        specs_list.append(spec)
    context = {
        'sku': sku,
        'categories': categories,
        'breadcrumb': breadcrumb,
        'category_id': sku.category_id,
        'spu': spu,
        'specs': specs_list
    }
#     获取模板对象
    template = loader.get_template('detail.html')
    html_str = template.render(context)
    file_path = settings.STATIC_FILE_PATH + "%s.html" % sku_id
    print(file_path)
    with open(file_path, 'a', encoding='utf-8') as f:
        f.write(html_str)





